package com.ygl.controller;

import com.ygl.api.service.ItemService;
import com.ygl.base.controller.BaseController;
import com.ygl.constants.BaseApiConstants;
import com.ygl.constants.Constants;
import com.ygl.entity.UserEntity;
import com.ygl.manager.ShoppingCartManager;
import com.ygl.web.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author： ygl
 * @date： 2019/02/04
 * @Description：
 */
@Slf4j
@Controller
public class IndexController extends BaseController {
    // index页面
    public static final String INDEX = "index" + "";
    @Autowired
    private ItemService itemService;
    @Autowired
    private ShoppingCartManager shoppingCartManager;
    private static final String LGOIN = "login";

    /**
     * 首页
     *
     * @param request
     * @return
     */
    @RequestMapping("/index")
    public String index(HttpServletRequest request) {
        // 查询所有商品
        Map<String, Object> reusltMapItem = itemService.getIndexItem();
        Integer code = (Integer) reusltMapItem.get(BaseApiConstants.HTTP_CODE_NAME);
        if (code.equals(BaseApiConstants.HTTP_200_CODE)) {
            Map<String, Object> mapItem = (Map<String, Object>) reusltMapItem.get("data");
            request.setAttribute("mapItem", mapItem);
        }
        return INDEX;
    }

    /**
     * 加入购物车
     *
     * @return
     */
    @RequestMapping("/addShopping")
    @ResponseBody
    public Map<String, Object> addShopping(HttpServletRequest request, String itemId) {
        String token = CookieUtil.getUid(request, Constants.USER_TOKEN);
        if (StringUtils.isEmpty(token)) {
            return setResponseError("您没有登录,请先登录后,才可以加入到购物车.");
        }
        UserEntity userEntity = getUserEntity(token);
        if (userEntity == null) {
            return setResponseError("您没有登录,请先登录后,才可以加入到购物车.");
        }
        try {
            return shoppingCartManager.addShopping(userEntity.getId() + "", itemId);
        } catch (Exception e) {
            log.error("addShopping() ERROR:", e);
            return setResponseError("加入购物车失败,请稍后重试!");
        }

    }

}

